package com.mfsoft.camera;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.example.mpsoft.RecyclingImageView;
import com.mfsoft.model.ImageItem;
import com.mfsoft.model.JSONParser;
import com.mfsoft.utilities.Utils;
import com.mfsoft.utilities.Variables;

public class OpenImageActivity extends Activity implements OnClickListener {
	private Button btFrame, btEffect, btIcon, btText, btSave, btShare;
	// private ImageView ivOpenImage;
	private RecyclingImageView ivOpenImage;
	private AQuery aq;
	private Bitmap placehoder;

	private DialogOpenImage dialogOpenImage;
	private DialogShareImage dialogShareImage;
	Intent intent;
	public static final int LOAD_GALLERY = 1;
	public static final int CAMERA_DATA = 0;
	public static final int IMG_SERVER = 2;
	public static final int IMG_MYALBUM = 3;
	public static final int SETTINGS = 4;
	private Bitmap bmp;
	String imgPath;
	private AlertDialog alertDialog;
	private ProgressDialog pDialog;
	AlertDialog.Builder alert;
	private Utils utils;
//	private int imageSize;

	// server
	int userId = 22;
	int page = 1;

	// my album
	File file;
	private File[] imageFiles;

	// JSONArray result = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.open_image);
		initVars();
		initAlertNetworkSetting();
	}

	private void initVars() {
		btFrame = (Button) findViewById(R.id.btFrame);
		btEffect = (Button) findViewById(R.id.btEffect);
		btIcon = (Button) findViewById(R.id.btIcon);
		btText = (Button) findViewById(R.id.btText);
		btSave = (Button) findViewById(R.id.btSave);
		btShare = (Button) findViewById(R.id.btShare);
		ivOpenImage = (RecyclingImageView) findViewById(R.id.ivOpenImage);
		ivOpenImage.setScaleType(ImageView.ScaleType.CENTER_CROP);

		btFrame.setOnClickListener(this);
		btEffect.setOnClickListener(this);
		btIcon.setOnClickListener(this);
		btText.setOnClickListener(this);
		btSave.setOnClickListener(this);
		btShare.setOnClickListener(this);
		ivOpenImage.setOnClickListener(this);

		dialogOpenImage = new DialogOpenImage(OpenImageActivity.this);
		dialogOpenImage.show();
		alertDialog = new AlertDialog.Builder(OpenImageActivity.this).create();
		dialogShareImage = new DialogShareImage(OpenImageActivity.this);

		// params = new ArrayList<NameValuePair>();
		// imageFile = new ArrayList<File>();
		utils = new Utils(OpenImageActivity.this);
	}
	
	public int getImageSize(){
		int imgSize;
		if(utils.getScreenHeight()>utils.getScreenWidth()){
			imgSize = utils.getScreenWidth()/2;
		}else {
			imgSize = utils.getScreenHeight()/2;
		}
		return imgSize;
	}

	// click vao cac button va imageview
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ivOpenImage:
			dialogOpenImage.show();
			break;
		case R.id.btFrame:
			alertDialog.setMessage("btFrame");
			alertDialog.show();
			break;
		case R.id.btEffect:
			alertDialog.setMessage("btEffect");
			alertDialog.show();
			break;
		case R.id.btIcon:
			alertDialog.setMessage("btIcon");
			alertDialog.show();
			break;
		case R.id.btText:
			alertDialog.setMessage("btText");
			alertDialog.show();
			break;
		case R.id.btSave:
			alertDialog.setMessage("btSave");
			alertDialog.show();
			break;
		case R.id.btShare:
			dialogShareImage.show();
			break;
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// mo anh tu bo suu tap
		if (requestCode == LOAD_GALLERY && resultCode == RESULT_OK
				&& data != null) {
			Uri selectedImg = data.getData();
			String[] filePathColumn = { MediaStore.Images.Media.DATA };
			Cursor cursor = getContentResolver().query(selectedImg,
					filePathColumn, null, null, null);
			cursor.moveToFirst();
			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			imgPath = cursor.getString(columnIndex);
			cursor.close();
			bmp = BitmapFactory.decodeFile(imgPath);
			ivOpenImage.setImageBitmap(bmp);
//			bmp.recycle();
		} else if (requestCode == CAMERA_DATA && resultCode == RESULT_OK) {
			Bundle extras = data.getExtras();
			bmp = (Bitmap) extras.get("data");
			ivOpenImage.setImageBitmap(bmp);
//			bmp.recycle();
		} else if ((requestCode == IMG_SERVER) || (requestCode == IMG_MYALBUM)) {
			if (!(resultCode == RESULT_OK)) {
				// back dot ngot chua chon hinh
			} else {

				Bundle extras = data.getExtras();
				ImageItem imageItem = (ImageItem) extras.get("image");
				// System.out.println("link anh: " + imageItem.getImageUrl());
				if (imageItem.getImagePath().equals("")) {
					aq = new AQuery(OpenImageActivity.this);
					placehoder = aq.getCachedImage(R.drawable.loader);
					aq.id(ivOpenImage).image(imageItem.getImageUrl(), true,
							true, 0, 0, placehoder, AQuery.FADE_IN_NETWORK,
							1.0f);
				} else {
					imgPath = imageItem.getImagePath();
					// Toast.makeText(this, "path: " + imgPath,
					// Toast.LENGTH_LONG);
//					bmp = BitmapFactory.decodeFile(imgPath);
					bmp = imageItem.decodeSampleBitmapFromUri(imgPath, getImageSize(), getImageSize());
					ivOpenImage.setImageBitmap(bmp);
//					bmp.recycle();
				}
			}

		} else if (requestCode == SETTINGS) {

		}
		// } else if (requestCode == IMG_MYALBUM && resultCode == RESULT_OK) {
		// Bundle extras = data.getExtras();
		// ImageItem imageItem = (ImageItem) extras.get("myalbum image");
		// imgPath = imageItem.getImagePath();
		// // Toast.makeText(this, "path: " + imgPath, Toast.LENGTH_LONG);
		// bmp = BitmapFactory.decodeFile(imgPath);
		// ivOpenImage.setImageBitmap(bmp);
		//
		// }
	}

	// cac tham so gui den server
	public ArrayList<NameValuePair> setPostEntity(int userId, int page) {
		ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("command", "getmyalbum"));
		params.add(new BasicNameValuePair("userid", String.valueOf(userId)));
		params.add(new BasicNameValuePair("page", String.valueOf(page)));
		return params;
	}

	// kiem tra ket noi internet
	public boolean isConnected() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = cm.getActiveNetworkInfo();
		if (networkInfo != null && networkInfo.isConnected())
			return true;
		else
			return false;
	}

	// lay anh tu server
	public ArrayList<ImageItem> getImagesServer(int userId, int page) {
		// moi lan reset lai du list de lay du lieu
		Variables.imagesServer.clear();
		if (isConnected()) {
			pDialog = ProgressDialog.show(this, "Anh tu server", "Loading...");
			new ImageServerTask().execute(userId, page);
			// System.out.println("album size: " + Variables.album.size());

		} else {
			// Toast.makeText(OpenImageActivity.this,
			// "Khong co ket noi Internet. Vui long mo ket noi Internet.",
			// Toast.LENGTH_LONG).show();
			// intent = new Intent(OpenImageActivity.this,
			// OpenImageTabsActivity.class);
			// intent.putExtra(Variables.FRAGMENT, 1);
			// startActivityForResult(intent, IMG_SERVER);
			alert.show();
		}

		return Variables.imagesServer;
	}

	// mo network setting
	public void initAlertNetworkSetting() {
		alert = new AlertDialog.Builder(this);
		alert.setTitle("Network setting");
		alert.setMessage("Vui long mo ket noi Internet?");

		alert.setPositiveButton("Settings",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
						// startActivity(i);
						startActivityForResult(intent, SETTINGS);
					}
				});

		alert.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				});

	}

	// mo album anh
	public ArrayList<ImageItem> getMyAlbum() {
		Variables.myAlbum.clear();
		// kiem tra sdcard
		if (!Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			Toast.makeText(this, "The nho chua san sang", Toast.LENGTH_LONG)
					.show();
		} else {
			pDialog = ProgressDialog.show(OpenImageActivity.this,
					"Album cua toi", "Loading...");
			file = new File(Environment.getExternalStorageDirectory()
					+ File.separator + Variables.ALBUMPHOTO);
			// mo thu muc mac dinh cua myalbum
			// neu ko co thi tao moi
			if (!file.exists()) {
				file.mkdirs();
			}
			new OpenMyAlbumTask().execute();
		}

		// new OpenMyAlbumTask().execute();
		// Toast.makeText(this, "album: " + Variables.myAlbum.size(),
		// Toast.LENGTH_LONG).show();

		return Variables.myAlbum;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getUserId() {
		return userId;
	}

	public void setUserId(int userId) {
		this.userId = userId;
	}

	// dialog open image
	class DialogOpenImage extends Dialog implements
			android.view.View.OnClickListener, OnItemSelectedListener {
		private Button btOk, btCancel;
		private Spinner spOpenImage;
		private int choose = -1;

		public int getChoose() {
			return choose;
		}

		public void setChoose(int choose) {
			this.choose = choose;
		}

		@Override
		protected void onCreate(Bundle savedInstanceState) {
			// TODO Auto-generated method stub
			super.onCreate(savedInstanceState);
			setContentView(R.layout.dialog_open_image);
			init();
		}

		private void init() {
			btOk = (Button) findViewById(R.id.btOk);
			btCancel = (Button) findViewById(R.id.btCancel);
			btOk.setOnClickListener(this);
			btCancel.setOnClickListener(this);

			spOpenImage = (Spinner) findViewById(R.id.spOpenImage);
			spOpenImage.setOnItemSelectedListener(this);

		}

		public DialogOpenImage(Context context) {
			super(context);
		}

		// cac button
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btOk:
				// user chon mo anh tu dau
				// dong dialog
				dismiss();
				chooseImages();
				break;
			case R.id.btCancel:
				setChoose(-1);
				dismiss();
				break;
			}

		}

		public void chooseImages() {
			switch (getChoose()) {
			case 0:
				// mo album anh
				getMyAlbum();
				break;
			case 1:
				// bo suu tap
				intent = new Intent(
						Intent.ACTION_PICK,
						android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
				startActivityForResult(intent, LOAD_GALLERY);
				break;
			case 2:
				// anh tu server
				getImagesServer(userId, page);
				break;
			case 3:
				// camera
				intent = new Intent(
						android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
				startActivityForResult(intent, CAMERA_DATA);
				break;
			case -1:
				break;
			}
		}

		// spinner
		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1,
				int position, long itemId) {
			setChoose(position);
			// System.out.println("chon: " + getChoose());
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub

		}

	}

	// dialog share image
	class DialogShareImage extends Dialog implements
			android.view.View.OnClickListener {
		private Button btGoogle, btFacebook, btTwitter, btCancelShare;

		public DialogShareImage(Context context) {
			super(context);
			setContentView(R.layout.dialog_share_image);
		}

		public void initVar() {
			btGoogle = (Button) findViewById(R.id.btGoogle);
			btFacebook = (Button) findViewById(R.id.btFacebook);
			btTwitter = (Button) findViewById(R.id.btTwitter);
			btCancelShare = (Button) findViewById(R.id.btCancelShare);
			btGoogle.setOnClickListener(this);
			btFacebook.setOnClickListener(this);
			btTwitter.setOnClickListener(this);
			btCancelShare.setOnClickListener(this);

		}

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btGoogle:
				
				break;
			case R.id.btFacebook:
				break;
			case R.id.btTwitter:
				
				break;
			case R.id.btCancelShare:
				dismiss();
				break;
			}

		}

	}

	// asyntask lay anh tu server
	class ImageServerTask extends AsyncTask<Integer, Void, Void> {
		// can 2 tham so
		// private int userId;
		// private int page;

		@Override
		protected Void doInBackground(Integer... params) {
			// userId = params[0];
			// page = params[1];
			// System.out.println("id:" + params[0] + " page:" + params[1]);

			JSONParser jParser = new JSONParser();
			JSONObject jObject = jParser.getJSONFromUrl(Variables.URL,
					setPostEntity(params[0], params[1]));

			// lay array result
			try {
				// cho nay chac no ko hieu gi result la gi
				JSONArray jArray = jObject.getJSONArray(Variables.TAG_RESULT);
				// vong lap lay ra url cua cac image
				for (int i = 0; i < jArray.length(); i++) {
					JSONObject img = jArray.getJSONObject(i);

					Variables.imagesServer.add(new ImageItem(img
							.getString(Variables.TAG_IMAGEURL), img
							.getString(Variables.TAG_NAME), img
							.getString(Variables.TAG_SIZE), img
							.getString(Variables.TAG_DATE), ""));
				}
				// System.out.println("server: " +
				// Variables.imagesServer.size());
			} catch (JSONException e) {
				e.printStackTrace();
				this.cancel(true);
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// lay du lieu cua my album ve roi thi dong pDialog lai
			if (pDialog != null) {
				pDialog.dismiss();
			}
			if ((Variables.imagesServer == null)
					|| (Variables.imagesServer.size() == 0)) {
				Log.e("server", "ko get dc du lieu");
			} else {

				intent = new Intent(OpenImageActivity.this,
						OpenImageTabsActivity.class);
				// startActivity(intent);
				intent.putExtra(Variables.FRAGMENT, 1);
				startActivityForResult(intent, IMG_SERVER);
			}
			super.onPostExecute(result);
		}

	}

	// mo myalbum
	@SuppressLint("SimpleDateFormat")
	class OpenMyAlbumTask extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {

			if (file.isDirectory()) {
				imageFiles = file.listFiles();
				// System.out.println("album: " + imageFiles.size());
				// ko nen, cho vao string, tieng viet thi value-vn, tieng anh
				// value-en
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				for (int i = 0; i < imageFiles.length; i++) {
					Variables.myAlbum.add(new ImageItem("", imageFiles[i]
							.getName(), imageFiles[i].length() / 1024 + "kb",
							sdf.format(imageFiles[i].lastModified()),
							imageFiles[i].getAbsolutePath()));
				}
				// System.out.println("album: " + Variables.myAlbum.size());
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// lay du lieu cua my album ve roi thi dong pDialog lai
			if (pDialog != null) {
				pDialog.dismiss();
			}
			if ((Variables.myAlbum == null) || (Variables.myAlbum.size() == 0)) {
				Log.e("album", "ko get dc du lieu");
			} else {

				intent = new Intent(OpenImageActivity.this,
						OpenImageTabsActivity.class);
				intent.putExtra(Variables.FRAGMENT, 0);
				startActivityForResult(intent, IMG_MYALBUM);
			}
			super.onPostExecute(result);
		}

	}

}
